<template>
  <scroll-view class="seg-content" scroll-y scroll-x :style="getContentStyle()">
    <!-- 顶部的monitor和右侧按钮，默认显示   -->
    <u-sticky customNavHeight="0">
      <view>
        <progress
            style="width: 90%; padding-left: 5%"
            @click="changeMonitorBar"
            :percent="pageData.logMonitorComponentData.progress.toFixed(1)"
            :activeColor="getActiveColor()"
            stroke-width="3"
            show-info
            v-show="!pageData.logMonitorBarSwitch"/>
      </view>
      <seg-predict-log-monitor
          @click="changeMonitorBar"
          :show="pageData.logMonitorBarSwitch"
          :title="pageData.logMonitorComponentData.title"
          :type="pageData.logMonitorComponentData.type"
          :description="pageData.logMonitorComponentData.description"
      ></seg-predict-log-monitor>
    </u-sticky>

    <!-- 注意右侧栏的参数和pc有些许不同   -->
    <seg-right-button v-show="judge(deviceType.mobile)"></seg-right-button>
    <seg-right-menu v-show="judge(deviceType.mobile)">
      <view style="margin-top: 20px; height: 80%">
        <view style="margin-left: 3%">
          <u--text :text="getTranslate(2)" size="30"></u--text>
        </view>
        <seg-tab-swiper :inRightMenu="true" :headers="getTranslateForComponent(1)">
          <seg-service-action-select
              slot="0" type="mobile"
              @LongTaskStatusChange="washDataFromSegActionSelect"
              :pName="pageData.segContentComponentData.userChoiceName"
              :uNameEncode="pageData.segUploadComponentData.uNameEncode"
              :uNameToken="pageData.segUploadComponentData.token"
          ></seg-service-action-select>
          <seg-content-choice
              slot="1"
              type="mobile"
              :table-data="pageData.segContentComponentData.tableData"
              @show="detailClick"
          ></seg-content-choice>
          <seg-history-popup
              slot="2"
              :on-right-menu="true"
          ></seg-history-popup>
        </seg-tab-swiper>
      </view>
    </seg-right-menu>

    <!--
      不要修改这里的v-if和v-show，这是我的一个bug，原因就是v-if删除组建，满足条件后装载，触发mounted
      然后导致的结果就是重置了按钮的状态，然后无法下载
    -->
    <view v-if="showBigImgArea">
      <view v-if="freshBigArea">
        <seg-img-cube
            :img-cube-tabs="getTranslateForComponent(0)"
            :albumData="pageData.remoteImgData.cubeAlbumData"
        ></seg-img-cube>
      </view>
    </view>
    <view v-show="!showBigImgArea">
      <uni-table border stripe style="overflow:visible;">
        <uni-tr>
          <uni-td align="left">
            <seg-content-group>
              <template>
                <view>
                  <seg-upload
                      @uploadStatusUpdate="washDataFromUpload"
                  ></seg-upload>
                </view>
              </template>
            </seg-content-group>
          </uni-td>
          <uni-td align="left" v-show="stateJudge(statusMode.desktop)">
            <view>
              <seg-service-action-select
                  @LongTaskStatusChange="washDataFromSegActionSelect"
                  :pName="pageData.segContentComponentData.userChoiceName"
                  :uNameEncode="pageData.segUploadComponentData.uNameEncode"
                  :uNameToken="pageData.segUploadComponentData.token"
              ></seg-service-action-select>
            </view>
          </uni-td>
        </uni-tr>
        <uni-tr style="background-color: white">
          <uni-td align="left" v-show="stateJudge(statusMode.desktop)">
            <view>
              <seg-content-choice
                  :table-data="pageData.segContentComponentData.tableData"
                  @show="detailClick" @delete="detailDelete"
              ></seg-content-choice>
            </view>
          </uni-td>
          <uni-td align="left">
            <view v-if="freshBigArea && showBigImgArea === false">
              <seg-img-cube
                  :img-cube-tabs="getTranslateForComponent(0)"
                  :albumData="pageData.remoteImgData.cubeAlbumData"
              ></seg-img-cube>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>

    </view>
  </scroll-view>
</template>

<script>
import SegUpload from "../../components/seg-upload/seg-upload";
import SegServiceActionSelect from "../../components/seg-service-action-select/seg-service-action-select";
import testData from "../../api/testData";
import SegContentChoice from "../../components/seg-content-choice/seg-content-choice";
import SegImgCube from "../../components/seg-img-cube/seg-img-cube";
import calCommon from "../../utils/winCal/calCommon";
import appConfig from "../../api/appConfig";
import SegPredictLogMonitor from "../../components/seg-predict-log-monitor/seg-predict-log-monitor";
import SegRightMenu from "../../components/seg-rightmenu/seg-rightmenu";
import SegTabSwiper from "../../components/seg-tab-swiper/seg-tab-swiper";
import SegContentGroup from "../../components/seg-content-group/seg-content-group";
import flaskApi from "../../api/flaskApi";
import statusJudge from "../../utils/monitor/statusJudge";
import flaskService from "../../api/modules/flaskService";
import {mapState} from "vuex";
import SegRightButton from "../../components/seg-right-button/seg-right-button";
import language from "../../api/language";
import SegHistoryPopup from "../../components/seg-history-popup/seg-history-popup";
import middleWareService from "../../api/modules/middleWareService";

export default {
  name: "arcusmain",
  components: {
    SegHistoryPopup,
    SegRightButton,
    SegContentGroup,
    SegTabSwiper,
    SegRightMenu, SegPredictLogMonitor, SegImgCube, SegContentChoice, SegServiceActionSelect, SegUpload},
  mixins: [calCommon, statusJudge],
  computed: {
    ...mapState('app', ['showBigImgArea', 'nowLanguage', 'winSize']),
    ...mapState('componentCommunicate', ['clickUpload', 'historyToken', 'historyImage']),
    ...mapState('user', ['userInfo'])
  },
  watch: {
    userInfo(newVal, oldVal){
      // 这个是登录后，状态改变
      this.pageData.segUploadComponentData.uNameEncode = btoa(encodeURIComponent(this.userInfo.userName))
    },
    historyToken(newVal, oldVal){
      this.pageData.segUploadComponentData.token = newVal
    },
    historyImage(newVal, oldVal){
      let imgArray = JSON.parse(newVal)
      let dataArray = []
      for(let i = 0; i < imgArray.length; i++){
        dataArray.push({ name: imgArray[i]})
      }
      this.pageData.segContentComponentData.tableData = {
        line: dataArray
      }
    },
    nowLanguage(newVal, oldVal){
      // this.getRemoteValue()
      this.changeCubeLanguage()
    },
    clickUpload(newVal, oldVal){
      this.pageData.remoteImgData.cubeAlbumData = testData.imgCubeListDataDefault
    },
    winSize(newVal, oldVal){
      this.freshArea()
    }
  },
  mounted() {
    this.imgCal()
    this.tableCal()
    // this.getRemoteValue()
    this.pageData.logMonitorComponentData.title = this.getTranslate(0)
    this.pageData.logMonitorComponentData.description = this.getTranslate(1)

    // 这个是已经登录直接获取
    this.pageData.segUploadComponentData.uNameEncode = btoa(encodeURIComponent(this.userInfo.userName))
  },
  beforeDestroy() {
    this.clearRemoteInterval()
  },
  data(){
    return {
      freshBigArea: true,
      deviceType: appConfig.deviceType,
      statusMode: appConfig.calMode,
      pageData: {  // 维护所有组件的数据结构,其余组件大部分时候应该只以显示为主
        // seg-upload组建回传的信息
        segUploadComponentData: {
          total: Object,
          list: Object,
          errorList: Object,
          token: '',  // 这两个被content-select使用
          uNameEncode: ''
        },
        // seg-content-choice需要的信息
        segContentComponentData: {
          tableData: {  // 从seg-upload修改过的信息
            line: []
          },
          userChoiceName: "",  // 用户选择的图像名称
          userDeleteName: ""   // 用户选择需要删除的图片
        },
        logMonitorBarSwitch: true,  // 切换进度栏杆的组建
        logMonitorComponentData: {
          progress: 0,
          description: "arcus系统实时为您服务",
          title: "Arcus系统",
          type: "primary"
        },
        remoteImgData: {
          // 存储远程数据结构,用于seg-img-cube的会显
          intervalObj: Object,
          cubeAlbumData: testData.imgCubeListDataDefault  // 常规的图像显示
        }
      }
    }
  },
  methods: {
    changeCubeLanguage(){
      // 替换imgCube数据缓冲区中的文本信息
      // debugger
      let cubeDataArray = this.pageData.remoteImgData.cubeAlbumData
      if(cubeDataArray.length > 0){
        // id0
        cubeDataArray[0].nameList = this.getTranslate(3)
        cubeDataArray[0].nameMobileList = this.getTranslate(4)

        // id1
        cubeDataArray[1].nameList = this.getTranslate(10)
        cubeDataArray[1].nameMobileList = this.getTranslate(11)
        if (cubeDataArray[1].hasOwnProperty("echartsData")){
          cubeDataArray[1].echartsData[0].categories = this.getTranslate(5)
          cubeDataArray[1].echartsData[0].series[0].name = this.getTranslate(6)
          cubeDataArray[1].echartsData[0].series[1].name = this.getTranslate(6)
        }


        // id2
        cubeDataArray[2].nameList = this.getTranslate(8)
        cubeDataArray[2].nameMobileList = this.getTranslate(9)
        if (cubeDataArray[2].hasOwnProperty("echartsData")){
          cubeDataArray[2].echartsData[0].series[0].name = this.getTranslate(6)
          cubeDataArray[2].echartsData[0].series[1].name = this.getTranslate(7)
          cubeDataArray[2].echartsData[1].series[0].name = this.getTranslate(6)
          cubeDataArray[2].echartsData[1].series[1].name = this.getTranslate(7)
        }

        // write back
        this.pageData.remoteImgData.cubeAlbumData = cubeDataArray
      }
    },
    freshArea(){
      this.freshBigArea = false
      setTimeout(()=>{
        this.freshBigArea = true
      }, 100)
    },
    getTranslate(posIndex){
      let langDict = language.getTranslate(language.arcusmain)
      if (posIndex === 0){
        return langDict.welcome
      }else if(posIndex === 1){
        return langDict.arcusServes
      }else if(posIndex === 2){
        return langDict.shortcutControl
      }else if(posIndex === 3){
        return langDict.nameList
      }else if(posIndex === 4){
        return langDict.nameMobileList
      }else if(posIndex === 5){
        return langDict.categories
      }else if(posIndex === 6){
        return langDict.originalImage
      }else if(posIndex === 7){
        return langDict.enhancedImage
      }else if(posIndex === 8){
        return langDict.nerveNameList
      }else if(posIndex === 9){
        return langDict.nerveNameMobileList
      }else if(posIndex === 10){
        return langDict.systematicsNameList
      }else if(posIndex === 11){
        return langDict.systematicsNameMobileList
      }else if(posIndex === 12){
        return langDict.deleteFileFail
      }else if(posIndex === 13){
        return langDict.remoteReadFail
      }
    },
    getTranslateForComponent(posIndex){
      if(posIndex === 0){
        if(language.langJudge('CHI')) return appConfig.imgCubeTabs
        else return appConfig.imgCubeTabsEng
      }else if(posIndex === 1){
        if(language.langJudge('CHI')) return appConfig.rightMenu
        else return appConfig.rightMenuEng
      }
    },

    getContentStyle(){
      if(this.judge(appConfig.calMode.mobileNoLeft)) return {'position': 'absolute'}
      else return {'position': 'relative'}
    },
    getActiveColor(){
      if(this.pageData.logMonitorComponentData.type !== 'error') return '#00FF00'
      else return '#FF0000'
    },
    changeMonitorBar(){
      // debugger
      this.pageData.logMonitorBarSwitch = !this.pageData.logMonitorBarSwitch
    },
    washDataFromUpload(data){
      this.pageData.segUploadComponentData = data
      let dataArray = []
      for(let index = 0; index < data.list.length; index++){
        let eachMonitor = data.list[index]
        if(eachMonitor.status === 'success'){
          dataArray.push({ name: eachMonitor.name })
        }
      }
      this.pageData.segContentComponentData.tableData = {
        line: dataArray
      }
    },
    washDataFromSegActionSelect(data){
      // debugger
      this.pageData.logMonitorComponentData = data
      this.pageData.logMonitorComponentData.title = this.pageData.logMonitorComponentData.title + '(' + this.pageData.logMonitorComponentData.progress + ")"
    },
    detailClick(name){
      this.pageData.segContentComponentData.userChoiceName = name
      this.getRemoteValue()
    },
    detailDelete(name){
      // debugger
      this.pageData.segContentComponentData.userDeleteName = name

      let uName = this.pageData.segUploadComponentData.uNameEncode
      let token = this.pageData.segUploadComponentData.token
      let img_name = name
      const success = (res)=>{
        for (let i = 0; i < this.pageData.segContentComponentData.tableData.line.length; i++){
          let d = this.pageData.segContentComponentData.tableData.line[i]
          if (d.name === img_name){
            this.pageData.segContentComponentData.tableData.line.splice(i, 1)
            break
          }
        }
      }
      const fail = (res) => {
        uni.showModal({
          title: 'Error',
          content: this.getTranslate(12) + "，log: " + JSON.stringify(res),
          showCancel: false
        })
      }
      flaskService.flaskFileDelete(uName, token, name, success, fail)

      const middleWareFail = (res)=>{
        uni.showModal({
          title: 'Error',
          content: res.data.msg,
          showCancel: false
        })
      }

      const middleWareSuccess = (res)=>{
        debugger
        if (res.data.code !== 200){
          middleWareFail(res)
        }
      }

      middleWareService.historyRecordDelete(this.userInfo.userName, token, name, middleWareSuccess, middleWareFail)


    },
    getRemoteValue(){
      this.pageData.remoteImgData.intervalObj = setInterval(()=>{
        let that = this
        let formData = {
          user_name: this.pageData.segUploadComponentData.uNameEncode,
          // user_name: btoa(encodeURIComponent(this.userInfo.userName)),  // 第一次无法读取历史的bug
          token: this.pageData.segUploadComponentData.token,
          img_name: this.pageData.segContentComponentData.userChoiceName
        }
        uni.request({
          url: flaskApi.PREDICT_GET,
          method: "POST",
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: formData,
          success: (res) => {
            let hasDone = true
            let jsonData = res.data
            that.pageData.remoteImgData.cubeAlbumData = []
            // TODO 懒得优化版
            // 注意分开来写，否则一个满足要求后，后面就不在计算
            if (!that.parserSeg(jsonData)){
              hasDone = false
            }
            if (!that.parserGrade(jsonData)){
              hasDone = false
            }
            if (!that.parserVascular(jsonData)){
              hasDone = false
            }
            if (!that.parserInteract(jsonData)){
              hasDone = false
            }
            if(hasDone){
              that.clearRemoteInterval()
            }
          },
          fail: (res) => {
            console.log(res)
            uni.showModal({
              title: 'Error',
              content: this.getTranslate(13) + '，log: ' + JSON.stringify(res),
              showCancel: false
            })
            that.clearRemoteInterval()
          }
        })

      }, 800)
    },
    parserSeg(jsonData){
      // ----------------- 原图以及增强图 --------
      let hasDone = true
      let that = this
      let id0 = {
        id: "0",
        imgList: [],
        mobileList: [],
        nameList: this.getTranslate(3),
        nameMobileList: this.getTranslate(4)
      }
      let temp = that.makeList(jsonData.segmentation.f0, true)
      let temp1 = that.makeList(jsonData.segmentation.f0, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id0.imgList.push(temp.array); id0.mobileList.push(temp1.array)
      // 分割图
      temp = that.makeList(jsonData.segmentation.f1, true)
      temp1 = that.makeList(jsonData.segmentation.f1, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id0.imgList.push(temp.array); id0.mobileList.push(temp1.array)

      that.pageData.remoteImgData.cubeAlbumData.push(id0)
      return hasDone
    },
    parserGrade(jsonData){
      // ----------------- 弯曲度分级 -------------
      let that = this
      let temp = {}
      let temp1 = {}
      let hasDone = true
      let id1 = {
        id: "1",
        imgList: [],
        mobileList: [],
        echartsData: [
          {
            categories: this.getTranslate(5),
            series: [
              {
                name: this.getTranslate(6),
                data: [0, 0]
              },
              {
                name: this.getTranslate(7),
                data: [0, 0]
              }
            ]
          }
        ],
        nameList: this.getTranslate(10),
        nameMobileList: this.getTranslate(11)
      }
      // 分级投影
      temp = that.makeList(jsonData.segmentation.f2, true)
      temp1 = that.makeList(jsonData.segmentation.f2, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id1.imgList.push(temp.array); id1.mobileList.push(temp1.array)
      // 分级的热力图
      temp = that.makeList(jsonData.segmentation.f3, true)
      temp1 = that.makeList(jsonData.segmentation.f3, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id1.imgList.push(temp.array); id1.mobileList.push(temp1.array)
      // 分级的计算数据
      // debugger
      temp = jsonData.segmentation.f2_1
      if(temp[0] !== '') {
        let t = JSON.parse(temp[0])
        id1.echartsData[0].series[0].data = [t.probabilities.toFixed(3), t.level]
      } else {
        hasDone = false
        id1.echartsData[0].series[0].data = [0, 0]
      }
      if(temp[1] !== '') {
        let t = JSON.parse(temp[1])
        id1.echartsData[0].series[1].data = [t.probabilities.toFixed(3), t.level]
      } else {
        hasDone = false
        id1.echartsData[0].series[1].data = [0, 0]
      }
      that.pageData.remoteImgData.cubeAlbumData.push(id1)
      return hasDone
    },
    parserVascular(jsonData){
      // debugger
      // ---------- vascular可视化部分 -------------
      let that = this
      let temp = {}
      let temp1 = {}
      let hasDone = true
      let id2 = {
        id: "2",
        imgList: [],
        mobileList: [],
        echartsData: [
          {
            categories: ["0", "20", "40", "60", "80", "100", "120", "140", "160", "180"],
            series: [
              {
                name: this.getTranslate(6),
                data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
              },
              {
                name: this.getTranslate(7),
                data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
              }
            ]
          },
          {
            categories: ["CNFL", "CNFD", "CTBD", "CNBD"],
            series: [
              {
                name: this.getTranslate(6),
                data: [0, 0, 0, 0]
              },
              {
                name: this.getTranslate(7),
                data: [0, 0, 0, 0]
              }
            ]
          }
        ],
        nameList: this.getTranslate(8),
        nameMobileList: this.getTranslate(9)
      }
      // 联通域
      temp = that.makeList(jsonData.vascular.f0, true)
      temp1 = that.makeList(jsonData.vascular.f0, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id2.imgList.push(temp.array); id2.mobileList.push(temp1.array)
      // 分支点
      temp = that.makeList(jsonData.vascular.f1, true)
      temp1 = that.makeList(jsonData.vascular.f1, false)
      if(!temp.hasDone || !temp1.hasDone) hasDone = false
      id2.imgList.push(temp.array); id2.mobileList.push(temp1.array)
      // 神经方向直方图
      temp = jsonData.vascular.f2
      if(temp[0] !== '') {
        id2.echartsData[0].series[0].data = JSON.parse(temp[0]).y
      } else {
        hasDone = false
        id2.echartsData[0].series[0].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      }
      if(temp[1] !== '') {
        id2.echartsData[0].series[1].data = JSON.parse(temp[1]).y
      } else {
        hasDone = false
        id2.echartsData[0].series[1].data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
      }
      // 参数量化结果
      temp = jsonData.vascular.f2_1
      if(temp[0] !== '') {
        let p = JSON.parse(temp[0])
        id2.echartsData[1].series[0].data = [p.CNFL.toFixed(3), p.CNFD.toFixed(3), p.CTBD.toFixed(3), p.CNBD.toFixed(3)]
      } else {
        hasDone = false
        id2.echartsData[1].series[0].data = [0, 0, 0, 0]
      }
      if(temp[1] !== '') {
        let p = JSON.parse(temp[1])
        id2.echartsData[1].series[1].data = [p.CNFL.toFixed(3), p.CNFD.toFixed(3), p.CTBD.toFixed(3), p.CNBD.toFixed(3)]
      }
      else {
        hasDone = false
        id2.echartsData[1].series[1].data = [0, 0, 0, 0]
      }
      that.pageData.remoteImgData.cubeAlbumData.push(id2)
      return hasDone
    },
    parserInteract(jsonData){
      // debugger
      // 交互框的可视化部分
      let id3 = {
        id: "3",
        imgList: [],
        mobileList: [],
        interactValue: []
      }

      let hasDone = true

      let f3 = jsonData.vascular.f3  // 点和数值的集合
      let f3_1 = jsonData.vascular.f3_1  // 原图内容

      if (f3.length === 0 || f3_1.length === 0){
        return false
      }

      // 转换常规图像
      if (f3[0] === "" || f3_1[0] === ""){
        hasDone = false
      }else{
        id3.interactValue.push(this.convertInteractValue(f3[0], f3_1[0]))
      }

      if (f3[1] === "" || f3_1[1] === ""){
        hasDone = false
      }else{
        id3.interactValue.push(this.convertInteractValue(f3[1], f3_1[1]))
      }

      this.pageData.remoteImgData.cubeAlbumData.push(id3)

      return hasDone
    },
    convertInteractValue(pointValue, oriImgUrl){
      let oriNervePoints = []
      let oriNerveValue = []
      let f30 = JSON.parse(pointValue)

      for (let i = 0; i < f30.length; i++){
        let each_n = this.convertEachNerve(f30[i])
        oriNervePoints.push({
          id: f30[i].id.toString(),
          points: each_n,
          stroke: 'red',
          strokeWidth: 1,
          closed: true
        })
        oriNerveValue.push({
          length: f30[i].length,
          tangle: f30[i].tangle
        })
      }
      return {
        oriNervePoints: oriNervePoints,
        oriNerveValue: oriNerveValue,
        oriImgUrl: oriImgUrl
      }

    },
    convertEachNerve(nerve){
      let l = nerve["borderList"]
      let dot_l = JSON.parse(l)
      let draw_l = []
      for (let i = 0; i < dot_l.length; i++){
        let each_dot = dot_l[i]
        draw_l.push(each_dot[0])
        draw_l.push(each_dot[1])
      }
      return draw_l
    },
    makeList(arrayLike, isPC){
      if(!isPC){
        for(let index = 0; index < arrayLike.length; index++){
          let item = arrayLike[index]
          if (item === '') return {
            hasDone: false,
            array: arrayLike
          }
        }
        return {
          hasDone: true,
          array: arrayLike
        }
      }else{
        let hasDone = true
        let resultArray = []
        for(let index = 0; index < arrayLike.length; index++){
          let item = arrayLike[index]
          if (item === '') { hasDone = false}
          resultArray.push([item])
        }
        return {
          hasDone: hasDone,
          array: resultArray
        }
      }
    },

    clearRemoteInterval(){
      clearInterval(this.pageData.remoteImgData.intervalObj)
    }

  }
}
</script>

<style scoped>

</style>
